import { Handlers } from "$fresh/server.ts";
import { AdminState } from "../../_middleware.ts";
import { ensureDir } from "https://deno.land/std@0.167.0/fs/ensure_dir.ts";
import { copy } from "https://deno.land/std@0.167.0/streams/copy.ts";
import { join } from "https://deno.land/std@0.167.0/path/mod.ts";
import { extname } from "https://deno.land/std@0.167.0/path/mod.ts";
import { crypto } from "https://deno.land/std@0.167.0/crypto/mod.ts";

// 最大允许上传的图片大小（5MB）
const MAX_FILE_SIZE = 5 * 1024 * 1024;
// 允许的图片类型
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
// 图片存储路径
const UPLOAD_DIR = "./static/images/imgs";
// 图片URL前缀
const URL_PREFIX = "/images/imgs";

export const handler: Handlers<unknown, AdminState> = {
  async POST(req, ctx) {
    // 验证管理员身份
    if (!ctx.state.isAdmin) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { "Content-Type": "application/json" }
      });
    }
    
    try {
      // 确保上传目录存在
      await ensureDir(UPLOAD_DIR);
      
      // 解析multipart表单数据
      const formData = await req.formData();
      const file = formData.get("image") as File;
      
      // 验证文件是否存在
      if (!file) {
        return new Response(JSON.stringify({ error: "No image file provided" }), {
          status: 400,
          headers: { "Content-Type": "application/json" }
        });
      }
      
      // 验证文件类型
      if (!ALLOWED_TYPES.includes(file.type)) {
        return new Response(JSON.stringify({ 
          error: `Invalid file type. Allowed types: ${ALLOWED_TYPES.join(", ")}` 
        }), {
          status: 400,
          headers: { "Content-Type": "application/json" }
        });
      }
      
      // 验证文件大小
      if (file.size > MAX_FILE_SIZE) {
        return new Response(JSON.stringify({ 
          error: `File size exceeds maximum allowed size (${MAX_FILE_SIZE / 1024 / 1024}MB)` 
        }), {
          status: 400,
          headers: { "Content-Type": "application/json" }
        });
      }
      
      // 生成唯一文件名
      const fileExt = extname(file.name);
      const uniqueId = crypto.randomUUID().replace(/-/g, "");
      const timestamp = new Date().getTime();
      const fileName = `img_${timestamp}_${uniqueId}${fileExt}`;
      const filePath = join(UPLOAD_DIR, fileName);
      
      // 保存文件
      const buffer = await file.arrayBuffer();
      await Deno.writeFile(filePath, new Uint8Array(buffer));
      
      // 返回图片URL
      const imageUrl = `${URL_PREFIX}/${fileName}`;
      
      return new Response(JSON.stringify({ 
        success: true, 
        url: imageUrl,
        fileName: fileName,
        fileSize: file.size
      }), {
        status: 200,
        headers: { "Content-Type": "application/json" }
      });
      
    } catch (error) {
      console.error("Error uploading image:", error);
      return new Response(JSON.stringify({ error: "Failed to upload image" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
}; 